import React, { memo, useMemo, useRef, useCallback } from 'react';
import Formx from './../formx/Formx';
import { EditProps } from './interface';
import { FormxRefProps } from './../formx/interface';
import { Button, Drawer } from 'antd';

const footerStyle: any = {textAlign: "right", paddingRight: "16px"};
const btnStyle: any = {marginLeft: "8px"};

export default memo(({ visible, formItems, onCancel, initialValues, onOk, groupNumber, onRemove, onValuesChange, 
  labelCol, wrapperCol, layout, disabled, loading, formExtra }: EditProps) => {

  const formxRef = useRef<FormxRefProps>(null);

  const _onOk = useCallback(async () => {
    const values = await formxRef.current?.validateFields();
    onOk({ ...initialValues, ...values })
  }, [onOk, initialValues]);

  const _onRemove = useCallback(async () => {
    onRemove?.(initialValues)
  }, [onRemove, initialValues]);

  const Title = useMemo(() => {
    if (initialValues.id) return '编辑';
    return '新增';
  }, [initialValues]);

  const Footer = useMemo(() => ([
    // initialValues.id && onRemove && <Button onClick={_onRemove} danger key='delete'>删除</Button>,
    <Button onClick={onCancel}>取消</Button>,
    <Button loading={loading} onClick={_onOk} style={btnStyle} key='confirm' type='primary'>确定</Button>
  ]), [initialValues, _onOk, _onRemove, onRemove, loading]);

  return (
    <Drawer
      title={Title}
      placement="right"
      width="50%"
      destroyOnClose={true}
      onClose={onCancel}
      visible={visible}
      footer={Footer}
      maskClosable={false}
      footerStyle={footerStyle}
    >
      <Formx layout={layout || 'vertical'} labelCol={labelCol} wrapperCol={wrapperCol} onValuesChange={onValuesChange} extra={formExtra}
        noLangFormUi ref={formxRef} initialValues={initialValues} groupNumber={groupNumber || 3} disabled={disabled} formItems={formItems}/>
    </Drawer>
  )
})